package com.wisenet.controller.client.sportwear;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.wisenet.annotation.LoginValidate;
import com.wisenet.cache.SimpleCacheProvider;
import com.wisenet.controller.PlatformController;
import com.wisenet.entity.SportWearUser;
import com.wisenet.entity.WeixinPubno;
import com.wisenet.service.sportwear.SportWearUserService;
import com.wisenet.wx.util.WeixinUtil;

/**
 * 用户信息管理控制类
 * @author fzh
 */
@RestController
@RequestMapping("/sport/user")
public class SportUserController extends PlatformController {
	public static Logger logger = Logger.getLogger(SportUserController.class);
	@Autowired
	private SportWearUserService sportUserService;
	@Autowired
	private SimpleCacheProvider simpleCacheProvider;

	@LoginValidate(value = false)
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public @ResponseBody JSONObject getUserLogin(String code, String appid) {
		JSONObject json = getJsonResult(code);
		if (json.getBoolean(SUCCESS)) {
			// 获取小程序信息
			WeixinPubno pubno = simpleCacheProvider.get(appid);
			if (pubno == null) {
				json.put(SUCCESS, false);
				json.put(RESULT,  ERROR);
				json.put(MESSAGE, "APP不存在");
				return json;
			}
			// 小程序登录获取信息
			JSONObject result = WeixinUtil.getOpenIdAndSessionKey(code, pubno.getAppid(), pubno.getAppsecret());
			logger.info("result: " + result);
			if (result != null) {
				String openid = result.getString("openid");
				SportWearUser sportWearUser = sportUserService.findByUid(openid);
				if (sportWearUser == null) {
					sportWearUser = new SportWearUser();
					sportWearUser.setUid(openid);
					long id = sportUserService.save(sportWearUser);
					if (id > 0) {
						sportWearUser.setId(id);
					}
				}
				json.put("user", sportWearUser);
			}
		}
		return json;
	}

	@LoginValidate(value = false)
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public @ResponseBody JSONObject updateUser(@RequestBody SportWearUser param) {
		JSONObject json = getJsonResult(param.getId(), param.getUid(), param.getNickName(), param.getAvatarUrl());
		if (json.getBoolean(SUCCESS)) {
			SportWearUser sportWearUser = sportUserService.findByUid(param.getUid());
			if (sportWearUser == null) {
				json.put(SUCCESS, false);
				return json;
			}
			long success = sportUserService.update(param);
			if (success < 0) {
				json.put(SUCCESS, false);
				json.put(MESSAGE, "数据库报错");
			}
		}
		return json;
	}

	@Override
	protected String getBasePath() {
		return null;
	}

}
